
const fs = require('fs');

const express = require('express');
const multer = require('multer');
const app = express();
const app2 = express();
const scanCodeDic = {};
 
// 设置存储配置
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, 'uploads/') // 确保这个文件夹已经存在
  },
  filename: function (req, file, cb) {
    // console.log("filename=", file);
    
    // cb(null, file.originalname)// + '-' + Date.now()
    var ipstr = req.socket.remoteAddress.replace('::ffff:', '');
    ipstr = ipstr.replace(/\./g, '');
    console.log('ipstr---------->',ipstr);
    cb(null, ipstr+file.originalname)// + '-' + Date.now()
  }
})
 
const upload = multer({ storage: storage });

function readFiles(name){
  const p = new Promise( function(resolve, reject){
    //
    var nameArr = [];
    fs.readdir('uploads', (err, files) => {
      if (err) {
        console.error(err);
        resolve(nameArr);
      }
      
      files.forEach(file => {
        console.log(file);
        if(file.indexOf(name) != -1){
          nameArr.push(file);
        }
      });
      console.log("sdlkkslds,",nameArr);
      resolve(nameArr);
    })
  });
  return p;
}

 
//upload.single('myfile')
//upload.array('photos', 12)
// 处理 POST 请求，包含文件上传
app.post('/upload', upload.array('photos', 12), (req, res) => {
  // console.log(req.files)
  // return;
  // const file = req.file; // 上传的文件信息
  // const body = req.body; // 其他表单字段
  // console.log('------------------res>',res);
  // console.log('------------------req>',req);

  console.log('有人上传了照片--->',req.socket.remoteAddress);

  //方法1
  var arr = req.files;
  console.log('length=',arr.length)
  // 文件路径
  const filePath = 'download.html';
  // 文件内容
  var content = '<!DOCTYPE html><html><body>';
  for(var i=0; i<arr.length; i++){
    content += "<div><img src=\"uploads/"+arr[i].filename+"\" /></div>";
  }
  content += '</body></html>';
  // 创建或覆盖文件
  fs.writeFile(filePath, content, 'utf8', function(err) {
    if (err) {
        return console.log(err);
    }
    console.log('html文件创建成功！');
  });

  //方法2
  // var nameArr = [];
  // readFiles.then( data => {
  //   nameArr = data;
  //   console.log('nameArr2=', nameArr);

  //   // 文件路径
  //   const filePath = 'uploads/download.html';
  //   // 文件内容
  //   var content = '<!DOCTYPE html><html><body>';
  //   for(var i=0; i<nameArr.length; i++){
  //     content += "<div><img src=\""+nameArr[i]+"\" /></div>";
  //   }
  //   content += '</body></html>';
  //   // 创建或覆盖文件
  //   fs.writeFile(filePath, content, 'utf8', function(err) {
  //     if (err) {
  //         return console.log(err);
  //     }
  //     console.log('html文件创建成功！');
  //   });
  // });

  
  var ipstr = req.socket.remoteAddress.replace('::ffff:', '');
  ipstr = ipstr.replace(/\./g, '');
  scanCodeDic[ipstr] = false;

  res.send('http://116.62.214.126:3003/photo?ip=' + ipstr);
})
//查询是否扫码了下载照片二维码
app.get('/code', function (req, res) {
  var ipstr = req.socket.remoteAddress.replace('::ffff:', '');
  ipstr = ipstr.replace(/\./g, '');
  const flag = scanCodeDic[ipstr]+'';
  var obj = {scanned:flag};
  var str = JSON.stringify(obj);
  console.log(ipstr, obj)
  res.send(str);
})
 
app.listen(3001, () => {
  console.log('Server listening on port 3001');
})

//扫码访问监听
app2.listen(3003, () => {
  console.log('Server listening on port 3003');
})
app2.get('/photo', function (req, res) {

  // console.log("监听到有人访问了照片",req);
  console.log("监听到有人访问了照片2",req.socket.remoteAddress);

  // var ipstr = req.socket.remoteAddress.replace('::ffff:', '');
  // ipstr = ipstr.replace(/\./g, '');

  //url: '/photo?ip=34284932402',
  var ipstr = req.url.split('=')[1];
  scanCodeDic[ipstr] = true;

  var nameArr = [];
  readFiles(ipstr).then( data => {
    nameArr = data;
    console.log('nameArr2=', nameArr);


    // 文件路径
    const filePath = 'uploads/download.html';
    // 文件内容
    var content = '<!DOCTYPE html><html><body>';
    for(var i=0; i<nameArr.length; i++){
      //http://116.62.214.126:3002/photo?ip=11210253162
      content += "<div><img src=\"http://116.62.214.126:3002/photo/uploads/"+nameArr[i]+"\" /></div>";
    }
    content += '</body></html>';
    // // 创建或覆盖文件
    // fs.writeFile(filePath, content, 'utf8', function(err) {
    //   if (err) {
    //       return console.log(err);
    //   }
    //   console.log('html文件创建成功！');
    // });
    res.send(content);
  });
})


// var http = require("http");

// const server = http.createServer((req, res) => {
//     res.writeHead(200, {'Content-Type': 'text/plain'});
//     res.end('Hello Wossaarld大声\n');
//     console.log("收到了一条sd消息22222..."+res);
//   });
   
//   const PORT = 3001;
//   server.listen(PORT, () => {
//     //console.log('Server running at http://localhost:${PORT}/');
//     console.log("收到了一条消息...");

//   });

  /**  // 选项配置HTTP请求
const options = {
    hostname: 'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=ww621843749abbfb7a&corpsecret=kfcc4312597d8bb24ee',
    path: '/path',
    method: 'GET'
  };
   
  // 创建HTTP请求
  const req = http.request(options, (res) => {
    console.log('状态码: ${res.statusCode}');
   
    res.on('data', (d) => {
      //process.stdout.write(d);
      console.log(d);
    });
  });
   
  // 错误处理
  req.on('error', (e) => {
    console.error('请求遇到问题: ' + e);
  });
   
  // 结束请求
  req.end();**/